Predicting Bank Marketing Succuss on Term Deposit Subsciption#

Summary#

In this analysis, we attempt to build a predictive model aimed at determining whether a client will subscribe to a term deposit, utilizing the data associated with direct marketing campaigns, specifically phone calls, in a Portuguese banking institution.

After exploring on several models (logistic regression, KNN, decision tree, naive Bayers), we have selected the logistic regression model as our primary predictive tool. The final model performs fairly well when tested on an unseen dataset, achieving the highest AUC (Area Under the Curve) of 0.899. This exceptional AUC score underscores the model’s capacity to effectively differentiate between positive and negative outcomes. Notably, certain factors such as last contact duration, last contact month of the year and the clients’ types of jobs play a significant role in influencing the classification decision.

Introduction#

In the banking sector, the evolution of specialized bank marketing has been driven by the expansion and intensification of the financial sector, introducing competition and transparency. Recognizing the need for professional and efficient marketing strategies to engage an increasingly informed and critical customer base, banks grapple with conveying the complexity and abstract nature of financial services. Precision in reaching specific locations, demographics, and societies has proven challenging. The advent of machine learning has revolutionized this landscape, utilizing data and analytics to inform banks about customers more likely to subscribe to financial products. In this machine learning-driven bank marketing project, we explore how a particular Portuguese bank can leverage predictive analytics to strategically prioritize customers for subscribing to a bank term deposit, showcasing the transformative potential of machine learning in refining marketing strategies and optimizing customer targeting for financial institutions.

Data#

Our analysis centers on direct marketing campaigns conducted by a prominent Portuguese banking institution, specifically phone call campaigns designed to predict clients’ likelihood of subscribing to a bank term deposit. The comprehensive dataset provides a detailed view of these marketing initiatives, offering valuable insights into factors influencing client subscription decisions. The dataset, named ‘bank-full.csv,’ encompasses all examples and 17 inputs, ordered by date. The primary focus of our analysis is classification, predicting whether a client will subscribe (‘yes’) or not (‘no’) to a term deposit, providing crucial insights into client behavior in response to direct marketing initiatives. Through rigorous exploration of these datasets, we aim to uncover patterns and trends that can inform and enhance the effectiveness of future marketing campaigns.

Methods#

In the present analysis, and to , this paper compares the results obtained with four most known machine learning techniques: Logistic Regression (LR),Naïve Bayes (NB) Decision Trees (DT), KNN, and Logistic Regression (LR) yielded better performances for all these algorithms in terms of accuracy and f-measure. Logistic Regression serves as a key algorithm chosen for its proficiency in uncovering associations between binary dependent variables and continuous explanatory variables. Considering the dataset’s characteristics, which include continuous independent variables and a binary dependent variable, Logistic Regression emerges as a suitable classifier for predicting customer subscription in the bank’s telemarketing campaign for term deposits. The classification report reveals insights into model performance, showcasing trade-offs between precision and recall. While achieving an overall accuracy of 83%, the Logistic Regression model demonstrates strengths in identifying positive cases, providing a foundation for optimizing future marketing strategies.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import requests

from sklearn.preprocessing import OrdinalEncoder, StandardScaler, OneHotEncoder
from sklearn.model_selection import train_test_split, GridSearchCV, RandomizedSearchCV
from sklearn.metrics import confusion_matrix,f1_score, roc_auc_score, classification_report, recall_score, precision_score
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from sklearn import metrics

from imblearn.over_sampling import RandomOverSampler, SMOTE, ADASYN, BorderlineSMOTE, KMeansSMOTE
from imblearn.under_sampling import ClusterCentroids, RandomUnderSampler

import warnings
import sys

# Import functions from the src folder
sys.path.append('..')
from src.resample import re_sample
from src.data_viz import plot_variables
from src.compute_and_plot_roc_curve import compute_and_plot_roc_curve
from src.model_report import model_report
<jemalloc>: MADV_DONTNEED does not work (memset will be used instead)
<jemalloc>: (This is the expected behaviour if you are running under QEMU)

Analysis#

Data Import#

url = 'https://archive.ics.uci.edu/static/public/222/data.csv'

request = requests.get(url)
with open("../data/raw/bank-full.csv", 'wb') as f:
        f.write(request.content)

Global Config#

pd.set_option('display.max_columns', None)
pd.options.display.float_format = '{:.3f}'.format
RANDOM_STATE = 522
warnings.filterwarnings("ignore")

Pre-Exploration#

bank = pd.read_csv('../data/raw/bank-full.csv', sep=',')
bank.columns
Index(['age', 'job', 'marital', 'education', 'default', 'balance', 'housing',
       'loan', 'contact', 'day_of_week', 'month', 'duration', 'campaign',
       'pdays', 'previous', 'poutcome', 'y'],
      dtype='object')
bank.shape
(45211, 17)
bank.head()
age job marital education default balance housing loan contact day_of_week month duration campaign pdays previous poutcome y
0 58 management married tertiary no 2143 yes no NaN 5 may 261 1 -1 0 NaN no
1 44 technician single secondary no 29 yes no NaN 5 may 151 1 -1 0 NaN no
2 33 entrepreneur married secondary no 2 yes yes NaN 5 may 76 1 -1 0 NaN no
3 47 blue-collar married NaN no 1506 yes no NaN 5 may 92 1 -1 0 NaN no
4 33 NaN single NaN no 1 no no NaN 5 may 198 1 -1 0 NaN no
bank.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 45211 entries, 0 to 45210
Data columns (total 17 columns):
 #   Column       Non-Null Count  Dtype 
---  ------       --------------  ----- 
 0   age          45211 non-null  int64 
 1   job          44923 non-null  object
 2   marital      45211 non-null  object
 3   education    43354 non-null  object
 4   default      45211 non-null  object
 5   balance      45211 non-null  int64 
 6   housing      45211 non-null  object
 7   loan         45211 non-null  object
 8   contact      32191 non-null  object
 9   day_of_week  45211 non-null  int64 
 10  month        45211 non-null  object
 11  duration     45211 non-null  int64 
 12  campaign     45211 non-null  int64 
 13  pdays        45211 non-null  int64 
 14  previous     45211 non-null  int64 
 15  poutcome     8252 non-null   object
 16  y            45211 non-null  object
dtypes: int64(7), object(10)
memory usage: 5.9+ MB
bank.y.value_counts()/len(bank)
y
no    0.883
yes   0.117
Name: count, dtype: float64

Pay attention that the target is class-imbalanced

Train Test Split#

bank_train, bank_test = train_test_split(bank
                                        , test_size=0.2
                                        , random_state=RANDOM_STATE
                                        , stratify=bank.y
                                        )
bank_train.y.value_counts()/len(bank_train)
y
no    0.883
yes   0.117
Name: count, dtype: float64
X_train, y_train = bank_train.drop(columns=["y"]), bank_train["y"]
X_test, y_test = bank_test.drop(columns=["y"]), bank_test["y"]

Via stratified split, we managed to keep the distribution of the label in the original dataset.

EDA#

for i in list(bank_train.columns):
    print(f"{i:<10}->  {bank_train[i].nunique():<5} unique values")
age       ->  77    unique values
job       ->  11    unique values
marital   ->  3     unique values
education ->  3     unique values
default   ->  2     unique values
balance   ->  6601  unique values
housing   ->  2     unique values
loan      ->  2     unique values
contact   ->  2     unique values
day_of_week->  31    unique values
month     ->  12    unique values
duration  ->  1506  unique values
campaign  ->  47    unique values
pdays     ->  536   unique values
previous  ->  40    unique values
poutcome  ->  3     unique values
y         ->  2     unique values
bank_int = list(bank_train.select_dtypes(include = ['int64']).columns)
bank_str = list(bank_train.select_dtypes(include = ['object']).columns)
bank_categorical = bank_str+['day']
bank_categorical
['job',
 'marital',
 'education',
 'default',
 'housing',
 'loan',
 'contact',
 'month',
 'poutcome',
 'y',
 'day']

Data Visualization#

We plotted the distributions of each predictor from the training data set and grouped and coloured the distribution by class (yes:green and no:blue).

Categorical variables#

plot_variables(bank_train, bank_categorical, var_type='categorical', ignore_vars='y')

Continuous variables#

bank_continuous = bank_train[bank_int]

plot_variables(bank_train, bank_continuous, var_type='continuous')

Log continuous variables#

bank_log = ['balance', 'duration', 'campaign', 'pdays', 'previous']
plot_variables(bank_train, bank_continuous, var_type='log')

Preprocessing#

In this section, we are defining lists with the names of the features according to their type.

numeric_features = bank.select_dtypes('number').columns.tolist()
categorical_features = ['job', 'marital', 'contact', 'month', 'poutcome']
ordinal_features = ['education']
binary_features = ['default', 'housing', 'loan']
drop_features = []
target = "y"

Then, we define all the transformations that have to be applied to the different columns. We define the order of the education levels as they belong to an ordinal variable and we create pipelines to manage nulls before each transformation. All of the transformations impute the most frequent value except for the numeric transformer, which imputes the median value.

education_levels = ['tertiary', 'secondary', 'primary']
ordinal_transformer = make_pipeline(SimpleImputer(strategy="most_frequent"),
                                    OrdinalEncoder(categories=[education_levels], dtype=int))

numeric_transformer = make_pipeline(SimpleImputer(strategy="median"), StandardScaler())

binary_transformer = make_pipeline(SimpleImputer(strategy="most_frequent"),
                                    OneHotEncoder(dtype=int, drop='if_binary'))

categorical_transformer = make_pipeline(SimpleImputer(strategy="most_frequent"),
                                        OneHotEncoder(handle_unknown="ignore", sparse_output=False))

Finally, we create a column transformer named preprocessor.

preprocessor = ColumnTransformer(
    transformers=[
        ('numeric', numeric_transformer, numeric_features),
        ('ordinal', ordinal_transformer, ordinal_features),
        ('binary', binary_transformer, binary_features),
        ('categorical', categorical_transformer, categorical_features),
        ('drop', 'passthrough', drop_features)
    ])

Fitting and transforming X_train#

transformed_train = preprocessor.fit_transform(X_train)
column_names = (
    numeric_features +
    ordinal_features +
    preprocessor.named_transformers_['binary'].named_steps['onehotencoder'].get_feature_names_out().tolist() +
    preprocessor.named_transformers_['categorical'].named_steps['onehotencoder'].get_feature_names_out().tolist() 
    )

X_train_trans = pd.DataFrame(transformed_train, columns=column_names)
X_train_trans.head(5)
age balance day_of_week duration campaign pdays previous education x0_yes x1_yes x2_yes x0_admin. x0_blue-collar x0_entrepreneur x0_housemaid x0_management x0_retired x0_self-employed x0_services x0_student x0_technician x0_unemployed x1_divorced x1_married x1_single x2_cellular x2_telephone x3_apr x3_aug x3_dec x3_feb x3_jan x3_jul x3_jun x3_mar x3_may x3_nov x3_oct x3_sep x4_failure x4_other x4_success
0 -0.463 -0.413 0.627 -0.733 -0.564 -0.411 -0.243 1.000 0.000 1.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 0.000 1.000 0.000 0.000
1 1.612 -0.072 -1.418 -0.679 0.072 -0.411 -0.243 1.000 0.000 0.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 1.000 0.000 0.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000
2 -0.086 -0.408 -1.418 -0.510 -0.564 -0.411 -0.243 1.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 0.000 0.000 1.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000
3 -0.369 -0.445 -1.178 -0.421 -0.564 -0.271 4.767 0.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 1.000
4 0.197 -0.292 1.228 -0.283 -0.564 -0.411 -0.243 1.000 0.000 1.000 1.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 0.000 1.000 0.000 0.000
y_train.head(5)
4868     no
29723    no
8911     no
34737    no
5657     no
Name: y, dtype: object

Transforming X_test#

transformed_test = preprocessor.transform(X_test)
column_names = (
    numeric_features +
    ordinal_features +
    preprocessor.named_transformers_['binary'].named_steps['onehotencoder'].get_feature_names_out().tolist() +
    preprocessor.named_transformers_['categorical'].named_steps['onehotencoder'].get_feature_names_out().tolist() 
    )

X_test_trans = pd.DataFrame(transformed_test, columns=column_names)
X_test_trans.head(5)
age balance day_of_week duration campaign pdays previous education x0_yes x1_yes x2_yes x0_admin. x0_blue-collar x0_entrepreneur x0_housemaid x0_management x0_retired x0_self-employed x0_services x0_student x0_technician x0_unemployed x1_divorced x1_married x1_single x2_cellular x2_telephone x3_apr x3_aug x3_dec x3_feb x3_jan x3_jul x3_jun x3_mar x3_may x3_nov x3_oct x3_sep x4_failure x4_other x4_success
0 1.235 -0.278 -1.178 -0.241 -0.246 -0.411 -0.243 1.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 0.000 0.000 1.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 0.000 1.000 0.000 0.000
1 0.480 -0.189 0.747 -0.471 0.390 -0.411 -0.243 1.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 1.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000
2 0.291 0.351 1.709 -0.483 -0.246 -0.411 -0.243 1.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 0.000 0.000 1.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000
3 1.517 -0.445 -0.215 -0.514 0.708 -0.411 -0.243 1.000 0.000 1.000 0.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 0.000 1.000 0.000 0.000
4 1.706 -0.110 -1.298 1.578 -0.564 -0.411 -0.243 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 1.000 0.000 0.000
y_test.head(5)
685       no
16193     no
17989     no
38058     no
24132    yes
Name: y, dtype: object

Resample#

Because it is a class-imbalanced issue, we decided to utilize some resample technique to boost the performance of our model. reference: https://imbalanced-learn.org/stable/under_sampling.html

X_tr, y_tr= re_sample(X_train, y_train, func='random_under_sample')
y_tr = y_tr.map({'yes':1, 'no':0})
y_test = y_test.map({'yes':1, 'no':0})
y_test
685      0
16193    0
17989    0
38058    0
24132    1
        ..
41512    1
40278    1
36878    0
11589    0
23945    0
Name: y, Length: 9043, dtype: int64
y_tr.value_counts()
y
0    4231
1    4231
Name: count, dtype: int64
X_tr
age job marital education default balance housing loan contact day_of_week month duration campaign pdays previous poutcome
23950 33 housemaid single tertiary no 1255 no no cellular 29 aug 511 4 -1 0 NaN
2856 60 technician married secondary no 2639 yes no NaN 14 may 483 2 -1 0 NaN
1759 43 admin. married secondary no 616 yes no NaN 9 may 168 2 -1 0 NaN
25999 49 unemployed married primary no 126 yes no cellular 19 nov 184 2 -1 0 NaN
7639 38 management single tertiary no -974 yes no NaN 30 may 120 3 -1 0 NaN
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
35956 59 retired married tertiary no 148 yes yes cellular 8 may 685 2 366 1 other
39773 45 blue-collar married secondary no 1723 no no cellular 1 jun 166 2 -1 0 NaN
44778 58 management married tertiary no 0 no no cellular 14 sep 358 2 -1 0 NaN
17794 46 admin. married secondary no 659 yes no telephone 29 jul 1127 11 -1 0 NaN
43294 35 blue-collar married secondary no 262 no no cellular 15 mar 427 1 181 3 success

8462 rows × 16 columns

models = {
    "Decision Tree": DecisionTreeClassifier(random_state=RANDOM_STATE),
    "KNN": KNeighborsClassifier(),
    "Naive Bayes": GaussianNB(),
    "Logistic Regression": LogisticRegression(max_iter=2000, random_state=RANDOM_STATE)
}

Modeling#

1. Logistic Regression#

First we applied a logistic regression model to our data. We used randomized search to find the best C parameter, as shown here (Figure 1):

Parameter Value
C 0.626443

Fig. 1 Best parameter for the Logistic Regression model.#

The best score generated by the model with the best parameter (Figure 2):

Metric Value
Best Score 0.904371

Fig. 2 Best score for the Logistic Regression model.#

Leveraging the logistic regression model with the best parameter, we got the below Receiver Operating Characteristic curve (Figure 3):

_images/lr_roc_auc.png

Fig. 3 ROC curve with AUC score for the Logistic Regression model.#

The classification report (Figure 4):

Precision Recall F1 Support
0 0.968 0.837 0.898 7985.000
1 0.392 0.793 0.524 1058.000
accuracy 0.832 9043.000
macro avg 0.680 0.815 0.711 9043.000
weighted avg 0.901 0.832 0.854 9043.000

Fig. 4 Classification report for the Logistic Regression model.#

The precision, recall, F1, AUC (Figure 5):

Model Recall Precision F1 AUC
Logistic Regression 0.793006 0.391690 0.524375 0.899340

Fig. 5 Key metrics for the Logistic Regression model.#

And the confusion matrix (Figure 6):

_images/lr_conf_matr.png

Fig. 6 Confusion matrix for the Logistic Regression model.#

Discussion:#

The presented classification report provides a detailed evaluation of a model’s performance on a binary classification task. Here are some key observations:

  • Precision and Recall: Precision measures the accuracy of positive predictions, indicating that when the model predicts a positive outcome, it is correct approximately 39% of the time. Recall, on the other hand, suggests that the model successfully identifies around 79% of the actual positive cases.

  • F1-Score: The F1-Score is the harmonic mean of precision and recall, providing a balance between the two. In this case, it is calculated at approximately 52%, reflecting a moderate balance between precision and recall.

  • Accuracy: The overall accuracy of the model is 83%, indicating the percentage of correctly predicted instances among all instances.

  • Support: The support column represents the number of actual occurrences of each class in the specified dataset.

  • Macro and Weighted Averages: The macro average calculates the unweighted average of precision, recall, and F1-score across classes, while the weighted average considers the support of each class. The macro average of the F1-score is around 71%, and the weighted average is approximately 85%.

  • AUC: The AUC for the logistic regression model is noted as approximately 90%. This suggests the model’s strong capability in distinguishing between the classes.

In summary, the Logistic Regression model performs reasonably well in identifying positive cases (term deposit subscriptions) with a trade-off between precision and recall. The overall evaluation metrics provide insights into the model’s strengths and areas for potential improvement.

2. KNN#

Then we implemented a KNN model on our dataset. To optimize the model, we still employed randomized search approach for determining the most effective parameters, n_neighbors and weights (Figure 7):

Parameter Value
n_neighbors 34
weights distance

Fig. 7 Best parameter for the KNN model.#

The corresponding best score of the optimized KNN model (Figure 8):

Metric Value
Best Score 0.898097

Fig. 8 Best score for the KNN model.#

By utilizing the KNN model optimized with the best parameters, we obtained the following ROC curve (Figure 9):

_images/KNN_roc_auc.png

Fig. 9 ROC curve with AUC score for the KNN model.#

The classification report (Figure 10):

Precision Recall F1 Support
0 0.966 0.857 0.908 7985.0
1 0.418 0.774 0.543 1058.0
accuracy 0.848 9043.0
macro avg 0.692 0.816 0.726 9043.0
weighted avg 0.902 0.848 0.866 9043.0

Fig. 10 Classification report for the KNN model.#

The precision, recall, F1, AUC (Figure 11):

Model Recall Precision F1 AUC
KNN 0.774102 0.418070 0.542923 0.896745

Fig. 11 Key metrics for the KNN model.#

And the confusion matrix (Figure 12):

_images/KNN_conf_matr.png

Fig. 12 Confusion matrix for the KNN model.#

Discussion:#

Based on the above results of the KNN model’s performance, we got some key findings:

  • Precision and Recall: For the positive class, the precision is about 42%, which indicates room for improvement in the accuracy of positive predictions. The positive class has a recall of approximately 77%, showing the model’s proficiency in detecting the actual positive instances.

  • F1-Score: For the positive class, the F1-score is around 54%, suggesting a moderate balance that could benefit from enhancement.

  • Accuracy: The model’s accuracy is reported at 85%, reflecting the proportion of correctly predicted instances out of all predictions made.

  • Support: The support metric indicates the actual occurrence of each class in the dataset, with 7985 instances for the negative class and 1058 for the positive class.

  • Macro and Weighted Averages: The macro average, which computes an unweighted mean across classes, presents an F1-score of approximately 73%, while the weighted average, taking into account the support for each class, is around 87%.

  • AUC: The AUC for the Decision Tree model is noted as approximately 90%

Summarizing the KNN model’s performance, it shows a strong ability in identifying negative cases with high precision and recall, while for positive cases, it demonstrates a fair detection rate with scope for improvement in precision.

3. Decision Tree#

We now implemented a decision tree and conducted a randomized search to identify the optimal parameters. The results of the best parameters are depicted here (Figure 13):

Parameter Value
max_depth 6
criterion entropy

Fig. 13 Best parameter for the Decision Tree model.#

With the best max_depth and criterion, we got the below best score (Figure 14):

Metric Value
Best Score 0.876534

Fig. 14 Best score for the Decision Tree model.#

Utilizing the logistic regression model with the optimal parameter, we generated the ROC curve presented below (Figure 15):

_images/dt_roc_auc.png

Fig. 15 ROC curve with AUC score for the Decision Tree model.#

The classification report (Figure 16):

Precision Recall F1 Support
0 0.97 0.792 0.872 7985.0
1 0.342 0.816 0.481 1058.0
accuracy 0.794 9043.0
macro avg 0.656 0.804 0.677 9043.0
weighted avg 0.897 0.794 0.826 9043.0

Fig. 16 Classification report for the Decision Tree model.#

The precision, recall, F1, AUC (Figure 17):

Model Recall Precision F1 AUC
Decision Tree 0.815690 0.341512 0.481450 0.868667

Fig. 17 Key metrics for the Decision Tree model.#

And the confusion matrix (Figure 18):

_images/dt_conf_matr.png

Fig. 18 Confusion matrix for the Decision Tree model.#

Discussion:#

Some key observations for the above decision tree model:

  • Precision and Recall: For the positive class, precision drops significantly to around 34%, suggesting that positive predictions are less reliable. However, the recall for the positive class is high at approximately 82%, which means the model is adept at capturing most of the actual positive cases.

  • F1-Score: For the positive class, the F1-score is around 48%, indicating a moderate balance with potential room for improvement.

  • Accuracy: The accuracy of the Decision Tree model is calculated at approximately 79%, which reflects the percentage of correctly predicted instances among all instances.

  • Support: The ‘support’ metric denotes the actual number of occurrences for each class in the dataset, with 7985 instances for the negative class and 1058 instances for the positive class.

  • Macro and Weighted Averages: The macro average, which provides an unweighted mean of precision, recall, and F1-score across classes, is calculated at around 68%. The weighted average, which accounts for the support of each class, is approximately 83%.

  • AUC: The AUC for the Decision Tree model is noted as approximately 87%.

In summary, the Decision Tree model demonstrates a strong ability to identify negative cases, with excellent precision and a good recall rate. While it identifies positive cases with high recall, the precision for positive predictions is quite low, suggesting a significant area for improvement.

4. Naive Bayes#

Finally we also tried a Naive Bayes model, and employed a randomized search to identify the most best parameters (Figure 19):

Parameter Value
var_smoothing 0.126892

Fig. 19 Best parameter for the Naive Bayes model.#

The best score generated by the model with the best parameter (Figure 20):

Metric Value
Best Score 0.844517

Fig. 20 Best score for the Naive Bayes model.#

Utilizing the Naive Bayes model fine-tuned with the optimal parameter, we generated the following ROC curve (Figure 21):

_images/nb_roc_auc.png

Fig. 21 ROC curve with AUC score for the Naive Bayes model.#

The classification report (Figure 22):

Precision Recall F1 Support
0 0.935 0.892 0.913 7985.0
1 0.397 0.535 0.456 1058.0
accuracy 0.850 9043.0
macro avg 0.666 0.714 0.685 9043.0
weighted avg 0.872 0.85 0.860 9043.0

Fig. 22 Classification report for the Naive Bayes model.#

The precision, recall, F1, AUC (Figure 23):

Model Recall Precision F1 AUC
Naive Bayes 0.534972 0.396914 0.455717 0.842733

Fig. 23 Key metrics for the Naive Bayes model.#

And the confusion matrix (Figure 24):

_images/nb_conf_matr.png

Fig. 24 Confusion matrix for the Naive Bayes model.#

Discussion:#

Findings from the evaluation of the Naive Bayes model’s performance:

  • Precision and Recall: For the positive class, the precision is significantly lower, at about 40%, showing that positive predictions are correct less than half of the time. The recall for the positive class is about 54%, indicating that the model is moderately effective at identifying actual positive cases.

  • F1-Score: For the positive class, the F1-score is about 46%, which indicates that there is room for improvement in balancing precision and recall for the positive predictions.

  • Accuracy: The model’s overall accuracy is 85%, reflecting the proportion of correctly predicted instances out of all predictions made.

  • Support: The ‘support’ value indicates the actual number of instances for each class in the dataset, with 7985 instances for the negative class and 1058 instances for the positive class.

  • Macro and Weighted Averages: The macro average, which calculates an unweighted mean of precision, recall, and F1-score across both classes, is around 68%. The weighted average, which accounts for the class distribution (support), is approximately 86%.

  • AUC: The Naive Bayes model has an AUC of approximately 84%.

In summary, the Naive Bayes model performs very well in identifying negative cases with high precision and recall, while it shows moderate effectiveness in identifying positive cases. The overall accuracy is quite high, and the AUC indicates a good discriminative ability. The model shows a strong performance on the negative class but there is a notable discrepancy in the positive class predictions, where both precision and recall could be improved for better balance and performance.

Performance of all models#

Aggregated results:#

We plotted the ROC curves for various models on a single graph (Figure 25) and combined the scores into one table for comparison (Figure 26):

_images/all_roc_auc.png

Fig. 25 ROC for all the tested models.#

Model Recall Precision F1 AUC
Logistic Regression 0.793006 0.391690 0.524375 0.899340
KNN 0.774102 0.418070 0.542923 0.896745
Decision Tree 0.815690 0.341512 0.481450 0.868667
Naive Bayes 0.534972 0.396914 0.455717 0.842733

Fig. 26 Metrics comparison for all the tested models.#

Comparison of models:#

The table provides an overview of key evaluation metrics for different machine learning models applied to a binary classification task, specifically predicting customer subscription to a term deposit in a bank’s telemarketing campaign. Let’s analyze each metric for each model:

Logistic Regression:#

Recall Score (Sensitivity): 79% indicates the model’s ability to identify actual positive cases, capturing a substantial portion of them. Precision: 39% reflects the accuracy of positive predictions, indicating that when the model predicts a positive outcome, it is correct about 39% of the time. F1-Score: 52% is the harmonic mean of precision and recall, providing a balanced measure, though still moderate. Area Under the Curve (AUC): 90% signifies the model’s overall ability to distinguish between positive and negative instances.

KNN (K-Nearest Neighbors):#

Recall Score (Sensitivity): 77% indicates the model’s effectiveness in capturing actual positive cases. Precision: 42% reflects the accuracy of positive predictions. F1-Score: 54% is the harmonic mean of precision and recall, showing a moderate balance. AUC: 90% signifies good overall discriminative ability.

Decision Tree:#

Recall Score (Sensitivity): 82% indicates a high ability to capture actual positive cases. Precision: 34% reflects the accuracy of positive predictions, but it’s lower compared to other models. F1-Score: 48% is the harmonic mean of precision and recall, showing a moderate balance. AUC: 87% indicates a good ability to distinguish between positive and negative instances.

Naive Bayes:#

Recall Score (Sensitivity): 53% indicates a moderate ability to capture actual positive cases. Precision: 40% reflects the accuracy of positive predictions. F1-Score: 46% is the harmonic mean of precision and recall, showing a moderate balance. AUC: 84% suggests a reasonable ability to discriminate between positive and negative instances.

In summary, the models show varying performance across metrics, while Logisitic Regression shows the best performance.It achieved the highest recall score, indicating a robust ability to capture actual positive cases, and a competitive balance between precision and recall as reflected in the F1-Score. Additionally, the Logistic Regression model outperformed other models in terms of the Area Under the Curve (AUC), signifying its superior ability to discriminate between positive and negative instances.

Feature Importance#

Finally, we chose Logistic Regression model and analysed the key features as determined by the model for predicting whether a client will subscribe to a term deposit.

The importance of the key features are demonstrated below (Figure 27):

_images/feat_imp.png

Fig. 27 Feature importance for the Logistic Regression model.#

Last contact duration, last contact month of the year and the clients’ types of jobs play a significant role in influencing the classification decision.

References#

Moro,S., Rita,P., and Cortez,P.. (2012). Bank Marketing. UCI Machine Learning Repository. https://doi.org/10.24432/C5K306.

Davis, J., & Goadrich, M. The Relationship Between Precision-Recall and ROC Curves. https://www.biostat.wisc.edu/~page/rocpr.pdf

Saito, T., & Rehmsmeier, M. (2015). The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced Datasets. PLOS ONE, 10(3), e0118432. https://doi.org/10.1371/journal.pone.0118432

Flach, P. A., & Kull, M. Precision-Recall-Gain Curves: PR Analysis Done Right. https://papers.nips.cc/paper/2015/file/33e8075e9970de0cfea955afd4644bb2-Paper.pdf

Dwork, C., Feldman, V., Hardt, M., Pitassi, T., Reingold, O., & Roth, A. (2015, September 28). Generalization in Adaptive Data Analysis and Holdout Reuse. https://arxiv.org/pdf/1506.02629.pdf

Turkes (Vînt), M. C. (Year, if available). Concept and Evolution of Bank Marketing. Transylvania University of Brasov Faculty of Economic Sciences. Retrieved from link to the PDF or ResearchGate. https://www.researchgate.net/publication/49615486_CONCEPT_AND_EVOLUTION_OF_BANK_MARKETING/fulltext/0ffc5db50cf255165fc80b80/CONCEPT-AND-EVOLUTION-OF-BANK-MARKETING.pdf

Moro, S., Cortez, P., & Rita, P. (2014). A data-driven approach to predict the success of bank telemarketing. Decis. Support Syst., 62, 22-31. https://repositorio.iscte-iul.pt/bitstream/10071/9499/5/dss_v3.pdf